#!/bin/sh
# shellcheck shell=dash disable=SC2169,SC3010,SC3014
#
# StromPi2 UPS Daemon starting and stopping
#

PATH=/sbin:/bin:/usr/sbin:/usr/bin
DAEMON="strompi2d"
PIDFILE="/var/run/${DAEMON}.pid"

test -x "/opt/strompi2d/strompi2d.sh" || exit 0

case $1 in
	start)
		echo -n "Starting StromPi2 UPS daemon: "

		# if a file /etc/config/strompi2 is found we assume
		# a StromPi2 to be present because there is no way to
		# autodetect it.
		if [[ -f /etc/config/strompi2 ]]; then

			# now start the daemon
			if start-stop-daemon --start --background --pidfile "${PIDFILE}" --make-pidfile --quiet --exec "/opt/strompi2d/strompi2d.sh"; then
				sleep 1

				# check if pid exists after start
				if [[ "$(/usr/bin/pgrep -f /opt/strompi2d/strompi2d.sh)" == "$(cat ${PIDFILE})" ]]; then
					echo "OK"
				else
					echo "FAIL"
				fi
			else
				echo "FAIL"
			fi
		else
			echo "disabled"
		fi
	;;

	stop)
		echo -n "Stopping StromPi2 UPS daemon: "
		if [[ -f ${PIDFILE} ]]; then
			if start-stop-daemon --stop --quiet --pidfile "${PIDFILE}"; then
				echo "OK"
			else
				echo "FAIL"
			fi
			rm -f ${PIDFILE}
		else
			echo "OK"
		fi
	;;

	restart|force-reload)
		$0 stop
		sleep 1
		$0 start
	;;

	*)
		echo "Usage: $0 {start|stop|restart|force-reload}" >&2
		exit 1
	;;
esac

exit 0
